package Day3;

import javax.swing.tree.TreeNode;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

/**
 * @projectName: AutumnTest
 * @package: Day3
 * @className: levelOrder
 * @author: Tongxinxin
 * @description: 二叉树的层序遍历
 * @date: 2025/8/27 16:33
 * @version: 1.0
 *
 * public class TreeNode {
 *       int val;
 *       TreeNode left;
 *       TreeNode right;
 *       TreeNode() {}
 *      TreeNode(int val) { this.val = val; }
 *      TreeNode(int val, TreeNode left, TreeNode right) {
 *          this.val = val;
 *  this.left = left;
 *  this.right = right;
 *  }
 * }
 */

public class levelOrder {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> list = new ArrayList<>();
        if(root == null) return list;
        Queue<TreeNode> linkList = new LinkedList<>();
        linkList.offer(root);

        while(!linkList.isEmpty()){
            int count = linkList.size();
            List<Integer> temp = new ArrayList<>();

            for(int i = 0;i<count;i++){
                TreeNode node = linkList.poll();
                temp.add(node.val);
                if(node.left != null){
                    linkList.offer(node.left);
                }
                if(node.right != null){
                    linkList.offer(node.right);
                }
            }

            list.add(temp);
        }
        return list;
    }

}
